package com.heima.crm.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.crm.common.contents.CommonMessageContent;
import com.heima.crm.common.result.PageResult;
import com.heima.crm.common.result.Result;
import com.heima.crm.common.utils.BaseContext;
import com.heima.crm.common.utils.YsRandomCodeUtils;
import com.heima.crm.mapper.TbCourseMapper;
import com.heima.crm.pojos.dtos.TbCourseDto;
import com.heima.crm.pojos.entity.TbActivity;
import com.heima.crm.pojos.entity.TbCourse;
import com.heima.crm.service.ITbCourseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * <p>
 * 课程管理表 服务实现类
 * </p>
 *
 * @author MonsterSong
 * @since 2023-07-15
 */
@Service
public class TbCourseServiceImpl extends ServiceImpl<TbCourseMapper, TbCourse> implements ITbCourseService {

    @Autowired
    private TbCourseMapper tbCourseMapper;

    /**
     * 课程管理分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public Result findPage(TbCourseDto dto) {
//        1.参数校验
        if (dto == null) {
            return Result.error(CommonMessageContent.INVALID_PARAMETER);//无效参数
        }
//        2.校验页码
        Integer page = dto.getPage();
        if (page == null || page < 0) {
            page = 1;
        }
        Integer size = dto.getSize();
        if (size == null || size < 0 || size > 100) {
            size = 10;
        }
//        3.分页
        Page<TbCourse> pageInfo = new Page<>(page, size);//        将page和size写死防狗判断操作
        LambdaQueryWrapper<TbCourse> lqw = new LambdaQueryWrapper<>();
//        4.模糊查询
        LocalDateTime start = null;
        LocalDateTime end = null;

        if (dto.getCreateTime() != null) {
            start = LocalDateTime.of(dto.getCreateTime(), LocalTime.MIN);
            end = LocalDateTime.of(dto.getCreateTime(), LocalTime.MAX);
        }
        lqw.like(StringUtils.isNotBlank(dto.getCode()), TbCourse::getCode, dto.getCode())
                .like(StringUtils.isNotBlank(dto.getName()), TbCourse::getName, dto.getName())
                .eq(StringUtils.isNotBlank(dto.getApplicablePerson()), TbCourse::getApplicablePerson, dto.getApplicablePerson())
                .between(start != null && end != null, TbCourse::getCreateTime, start, end)
                .eq(dto.getSubject() != null, TbCourse::getSubject, dto.getSubject())
                .orderByDesc(TbCourse::getCreateTime);
//        通过时间搜索
        page(pageInfo, lqw);
//        5.封装数据返回
        PageResult<TbCourse> result = new PageResult<TbCourse>(pageInfo.getTotal(), pageInfo.getRecords());

        return Result.success(result);
    }

    /**
     * 数据回显
     *
     * @param id
     * @return
     */
    @Override
    public Result findById(Long id) {
        if (id == null) {
            return Result.error(CommonMessageContent.INVALID_PARAMETER);
        }
        TbCourse tbCourse = tbCourseMapper.selectById(id);
        return Result.success(tbCourse);
    }

    /**
     * 课程数据修改
     *
     * @param tbCourse
     * @return
     */
    @Override
    public Result updateTbCourse(TbCourse tbCourse) {
//        参数校验
        if (tbCourse == null) {
            return Result.error(CommonMessageContent.PARAMETER_EXCEPTION);
        }
        tbCourse.setUpdateTime(LocalDateTime.now());
        tbCourse.setUpdateUser(BaseContext.getCurrentId());
//        校验学科或适应人群是否合法
        Long aLong = getaLong(tbCourse);
        if (aLong <= 0) {
            return Result.error("修改的课程学科或适应人群有误！");
        }
        tbCourseMapper.updateById(tbCourse);
        return Result.success("课程数据修改成功！");
    }

    /**
     * 防止乱添加课程学科和适用人群
     *
     * @param tbCourse
     * @return
     */
    private Long getaLong(TbCourse tbCourse) {
        LambdaQueryWrapper<TbCourse> lqw = new LambdaQueryWrapper<>();
        lqw.eq(tbCourse.getSubject() != null, TbCourse::getSubject, tbCourse.getSubject())
                .eq(tbCourse.getApplicablePerson() != null, TbCourse::getApplicablePerson, tbCourse.getApplicablePerson());
        Long aLong = tbCourseMapper.selectCount(lqw);
        return aLong;
    }

    /**
     * 删除课程
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Long id) {
        if (id == null) {
            return Result.error(CommonMessageContent.INVALID_PARAMETER);
        }
        tbCourseMapper.deleteById(id);
        return Result.success("删除成功！");
    }

    /**
     * 新增课程
     *
     * @param tbCourse
     * @return
     */
    @Override
    public Result addTbCourse(TbCourse tbCourse) {
        if (tbCourse == null) {
            return Result.error(CommonMessageContent.INVALID_PARAMETER);
        }
//        随机生成code
        String string = YsRandomCodeUtils.generateRandomString();
        tbCourse.setCode(string);
        tbCourse.setCreateTime(LocalDateTime.now());
        tbCourse.setCreateUser(BaseContext.getCurrentId());
//        课程名称重复判断
        LambdaQueryWrapper<TbCourse> lqw = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<TbCourse> eqName = lqw.eq(TbCourse::getName, tbCourse.getName());
//         返回的是查询到的相同名称的数据
        Long nameNum = tbCourseMapper.selectCount(eqName);
        if (nameNum > 0) {
            return Result.error(CommonMessageContent.ALREADY_EXISTS);// 数据已经存在
        }
//        校验学科或适应人群是否合法
        Long aLong = getaLong(tbCourse);
        if (aLong <= 0) {
            return Result.error("添加的课程学科或适应人群有误！");
        }
//        插入数据
        tbCourseMapper.insert(tbCourse);
        return Result.success("插入课程数据成功！");
    }

    /**
     * 添加合同时，根据购买学科查询购买的课程
     *
     * @param subject
     * @return
     */
    @Override
    public Result findSubjectById(Long subject) {
//        TODO 路径参数好像无用
        if (subject == null) {
            return Result.error(CommonMessageContent.INVALID_PARAMETER);
        }
        LambdaQueryWrapper<TbCourse> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TbCourse::getSubject, subject);
        List<TbCourse> tbCourses = tbCourseMapper.selectList(lqw);
//        应该是判断传入的路径参数是否无效，此方法还是要通过查询数据库返回的值为null判断
        if (tbCourses.size() <= 0) {
            return Result.error("没有id为：《" + subject + "》的学科课程！");
        }
        return Result.success(tbCourses);

    }
}
